package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * description:
 *
 * @Author caoshuaifeng
 * @Create 2025/3/3 19:06
 * @Version 1.0
 */
@Configuration
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    public MyGlobalFilter() {
        super();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        System.out.println("url"+url);
        //白名单
        if (url.contains("login")||url.contains("sendCode")||url.contains("phoneLogin")) {
            System.out.println("白名单"+url);
            return chain.filter(exchange);
        }
        //检查token
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            System.out.println("token不存在"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //解析token
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String tokenkey="token-"+userId;
        String RedisToken = stringRedisTemplate.opsForValue().get(tokenkey);
        if(RedisToken==null){
         System.out.println("token失效"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!token.equals(RedisToken)) {
          System.out.println("token不匹配"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //token续期
        stringRedisTemplate.expire(tokenkey, 15, TimeUnit.MINUTES);
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
